﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SqlLibrary;
using System.Xml;

namespace Ecopsy.DataTier
{
    /// <summary>
    /// EntityList - прогружающийся из SqlStatment
    /// </summary>
    public class SqlStatment_EntityList:EntityList 
    {
        protected SqlStatment _SqlStatment = null;        
        [EntityNonSerialized ]
        public virtual SqlStatment SqlStatment { get { return _SqlStatment; } set { _SqlStatment = value; } }

        public override void Load()
        {
            SecuretyContext SC = AppContext.GetSC(this.Def_SCName);
            try
            {
                if (null == _SqlStatment) return;

                _SqlStatment.PrepareStatment();
                string sql = _SqlStatment.GetStatment();
                
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();                
                cmd.CommandText = sql;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Connection = SC.Connection;
                SC.Connection.Open();
                XmlReader r = cmd.ExecuteXmlReader();
                if (null == r) return;
                XmlDocument d = new XmlDocument();
                d.Load(r);                
                if (null == d.FirstChild) return;
                this.Clear();
                this.ReadXml(d.FirstChild);
                foreach (Entity item in this ) item.SetHash();
            }
            catch
            {
                return ;
            }
            finally
            {
                SC.Connection.Close();
            }
        }

    }

}
